<?php
use Illuminate\Support\Facades\Mail;
use App\Mail\Basic;

/**
 * @param bool $redirect // 是否强制登录
 * @throws \App\Exceptions\NotLoginException
 * @return mixed
 * 获取登录的 uid
 */
function uid($redirect = false){
	$ticket = request('ticket');
	$uid = \App\Models\ClientUserTicket::where(['ticket'=>$ticket])->value('uid');
	if($redirect && empty($uid)){
		throw new \App\Exceptions\NotLoginException();
	}
	return $uid;
}

// 登录
function login($uid,$type=0){
	$clientUserTicket = new \App\Models\ClientUserTicket();
	$ticket = $clientUserTicket->login($uid);

	$data = $clientUserTicket->select('uid','ticket','rongcloud_token')->where(['ticket'=>$ticket])->first();

	$user = \App\Models\ClientUser::where(['id'=>$data->uid])->select('mobile','type')->first();
	$data->mobile = $user->mobile;
	$data->user_type = $user->type;
	$data->mobile_hidden = hidden_mobile($data->mobile);

	// 绑定的房屋名称
    if($type==0) {
        $house_first = \App\Models\ClientUserHouse::where(['uid' => $data->uid])->orderBy('id', 'desc')->first();
        $data->binded_house = \App\Models\ClientUserHouse::firstOrNew(['id' => $house_first->id])->detail()->name_long;
        $data->binded	= \App\Models\ClientUserHouse::where(['uid'=>$data->uid])->count() ? 1 : 0;
    }else{
        $roles_info = \App\Models\ShopStoreRoles::where(['uid'=>$data->uid])->orderBy('is_del','asc')->first();
        $data->status = 1;
        if(!$roles_info){
            $data->status=2;
            $data->store_type=1;
            return $data;
        }else{
            $data->store_type = \App\Models\ShopStore::where(['id'=>$roles_info['store_id']])->value('store_type');
        }
        if($roles_info['is_del']){
            throw new Exception('该账号已经被删除');
        }
        $store_id = $roles_info['store_id'];
        $data->status = \App\Models\ShopStore::where(['id'=>$store_id])->value('status');
    }
	return $data;
}

/**
 * @param $uid
 * 微信信息保存
 */
function wechat_update($uid){
	$var = false;
	$openid = request('openid');
	$unionid = request('unionid');
	$username = request('name');
	$avatar = request('iconurl');
	$gender = request('gender',1);
	if($gender == '男'){
		$gender = 1;
	}else if($gender == '女'){
		$gender = 0;
	}
	if($openid){
		$avatar = curl_avatar($avatar);
		$var = \App\Models\ClientUser::where(['id'=>$uid])->update([
			'openid'		=> $openid,
			'unionid'		=> $unionid,
//			'username'		=> $username,		// 不用改，是用户自己填写的
			'avatar'		=> $avatar,
			'gender'		=> $gender
		]);
	}
	return $var;
}

// 退出登录
function logout($uid = 0){
	$clientUserTicket = new \App\Models\ClientUserTicket();
	$status = $clientUserTicket->logout($uid);
	return $status;
}

/**
 * @param $url
 * @param $post_data
 * @param array $ssl
 * @return bool|string
 */
function curl_post($url,$post_data,$ssl = []){
	$post_header = [
		'form_params'	=> $post_data,
		'verify'		=> __DIR__.'/cainfo.pem',
//		'debug'			=> true,
	];
	$post_header = array_merge($post_header,$ssl);
	$client = new GuzzleHttp\Client(['timeout' => 30]);
	$response = $client->post($url,$post_header);
	if($response->getStatusCode() == 200){
		return $response->getBody()->getContents();
	}else{
		return false;
	}
}

/**
 * @param $url
 * @return bool|string
 */
function curl_get($url){
	$client = new GuzzleHttp\Client(['timeout' => 15]);
	$response = $client->get($url);
	if($response->getStatusCode() == 200){
		return $response->getBody()->getContents();
	}else{
		return false;
	}
}

/**
 * @param $url
 * @param string $type
 * @return bool|string
 * 下载头像
 */
function curl_avatar($url,$type = 'avatar'){
	$post_header = [
		'verify'		=> __DIR__.'/cainfo.pem',
	];
	$client = new GuzzleHttp\Client(['timeout' => 15]);
	$response = $client->get($url,$post_header);
	if($response->getStatusCode() == 200){
		$steam = $response->getBody()->getContents();
		$file_name_pre = '/storage/images/'.$type;
		if(!is_dir('.'.$file_name_pre)){
			mkdir('.'.$file_name_pre,0777,true);
		}
		$file_name_pre .= '/'.uniqid($type).'.png';
		file_put_contents('.'.$file_name_pre,$steam);
		return 'http://api.'.env('APP_DOMAIN').$file_name_pre;
	}else{
		return false;
	}
}

/**
 * 时间戳格式化成国内日期格式
 * @param null $time
 * @return false|string
 */
function time2date($time = null){
	return date('Y-m-d H:i:s',$time ?? request()->server('REQUEST_TIME'));
}
function time2date_date($time = null){
	return date('Y-m-d',$time ?? request()->server('REQUEST_TIME'));
}


// 刷新网页
function refresh($url){
	header("Location:$url");
	exit();
}

// 重定向并带post数据
function build_form($url,$post_data){
	$input_param = '';
	foreach($post_data as $k => $v){
		$input_param .= '<input type="hidden" name="'.$k.'" value="'.$v.'" />';
	}
	$html = <<<EOT
<meta charset="utf-8" />
<meta http-equiv="content-type" name="keywords" content="" />
<meta http-equiv="content-type" name="description" content="" />
<meta name="viewport" content="width=device-width, initial-scale=1,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no" />
<meta name="format-detection" content="telephone=no" />
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="black" />
<form method="post" action="$url" id="form_to_gaohuitong">
$input_param
<input type="submit" value="　" style="opacity:0" />
</form>
<script>document.getElementById('form_to_gaohuitong').submit();</script>
EOT;
	$html = str_replace("\r\n",'',$html);
	$html = str_replace(PHP_EOL,'',$html);
	return $html;
}

/**
 * 发送简易邮件，用于错误等报告
 * @param $to	// 收件人邮箱，支持数组添加多个收件人
 * @param $text	// 简易内容
 * @return bool
 */
function send_mail($to,$text){
//	dispatch(new \App\Jobs\SendMail($to,$text));
	if(is_array($to)){
		foreach($to as $v){
			Mail::to($v)->queue((new Basic($text))->onQueue('send_email'));
		}
	}else{
		Mail::to($to)->queue((new Basic($text))->onQueue('send_email'));
	}
	return true;
}

/**
 * @param $mobile
 * @param $template
 * @param $param
 * @param $cache_key
 * @return bool
 * 短信只有一个模板，就是发送验证码
 */
function send_message($mobile,$template,$param){
	$url = 'http://api.'.env('APP_DOMAIN').'/msg/message_sync';
	// 正式版才会真发送短信，否则直接成功
	if(env('APP_ENV') == 'online'){
		$return = curl_post($url,['mobile'=>$mobile,'template'=>$template,'param'=>$param]);
	}else{
		$return = 'success';
	}
	
	return $return == 'success' ? true : false;
}

/**
 * @param $uid
 * @param $title
 * @param $content
 * @param int $type		//1系统消息，2投诉回复，3物业通知，4订单消息
 * @return bool
 * 发送站内信
 */
function send_msg($uid,$title,$content,$type = 1){
	$add = [
		'uid'		=> $uid,
		'type_id'	=> $type,
		'title'		=> $title,
		'content'	=> $content,
	];
	$id = \App\Models\ClientUserMessage::create($add)->id;
	return $id;
}


/******************************************************** 隐藏数据部分 *******************************************************/
/**
 * @param $mobile
 * @return string;
 */
function hidden_mobile($mobile){
	$pre = substr($mobile,0,3);
	$last = substr($mobile,7);
	return $pre.'****'.$last;
}


/******************************************************** 接口通用返回部分 **************************************************/

/**
 * @param string $data
 * 清楚数据内的null
 */
function clear_null(&$data = ''){
//	if($data instanceof stdClass){
		$data = json_decode(json_encode($data),true);
//	}
	if($data === null || $data === false){
		$data = '';
	}
	if(is_array($data) && !empty($data)){
		foreach($data as &$v){
			if($v === null || $v === false){
				$v = '';
			}else if(is_array($v)){
				clear_null($v);
			}else if(is_string($v) && stripos($v,'.') === 0){
				$v = '0'.$v;
			}
		}
	}
}
/**
 * json API 返回成功
 * @param string $msg
 * @param array $data
 * @return array
 */
function json_success($msg = '',$data = []){
	$return = [
		'code'	=> '1',
		'msg'		=> $msg,
		'data'		=> $data,
		//'request_uri' => request('_cmd'),
	];
	clear_null($return['data']);
	return $return;
}
/**
 * json API 返回成功
 * @param string $msg
 * @param array $data
 * @return array
 */
function json_sussess_obj($msg='',$data=[]){

    $return = [
        'code'	=> '1',
        'msg'		=> $msg,
        'data'		=> $data,
        //'request_uri' => request('_cmd'),
    ];
    return $return;
}
/**
 * json API 返回失败
 * @param $msg
 * @param array $data
 * @return array
 */
function json_error($msg,$data = []){
	$msg = $msg ? : '服务器错误，请稍后重试';
	$return =  [
		'code'	=> '0',
		'msg'		=> $msg,
		'data'		=> $data,
		//'request_uri' => request('_cmd'),
	];
	clear_null($return['data']);
	return $return;
}

/**
 * json API 返回需要登录
 * @param $msg
 * @param array $data
 * @return array
 */
function json_login($msg = '',$data = []){
	$msg = $msg ? : '登录失效，请重新登录';
	$return =  [
		'code'	=> '2',
		'msg'		=> $msg,
		'data'		=> $data,
	];
	clear_null($return['data']);
	return $return;
}

/**
 * json API 根据变量自动判断返回成功或失败
 * @param $var
 * @param string $error_msg
 * @param string $success_msg
 * @param array $data
 * @return array
 */
function json_return($var,$error_msg = '服务器错误，请稍后重试',$success_msg = 'OK',$data = []){
	if($var === false || $var === null){
		return json_error($error_msg,$data);
	}else{
		return json_success($success_msg,$data);
	}
}



/********************************************************* 数据库方法封装部分 **************************************************/

/**
 * 检查事务状态成功与否
 * @param $status
 * @return bool
 */
function checkTrans($status){
	if(is_array($status)){
		foreach($status as $v){
			if(empty($v)){
				return false;
			}
		}
	}else{
		if(empty($status)){
			return false;
		}
	}
	return true;
}

/**
 * @param $field
 * @return string
 * mysql 时间戳查询时转成 timestamp 格式
 */
function from_unixtime($field){
	return 'from_unixtime('.$field.',\'%Y-%m-%d %H:%i:%s\') as '.$field;
}


/*********************************************************** 随机数部分 **********************************************************/

/**
 * 生成一个随机数字字符串，可用于验证码等
 * @param int $length
 * @return string
 */
function create_verify_code($length = 4){
	$rand = [];
	for($i=0;$i<$length;$i++){
		$rand[] = rand(0,9);
	}
	$rand_str = implode('',$rand);
	return $rand_str;
}

/**
 * @return string
 * 生成唯一guid规则的字符串
 */
function uuid() {
	if (function_exists ( 'com_create_guid' )) {
		$uuid = com_create_guid ();
	} else {
		mt_srand ( ( double ) microtime () * 10000 ); //optional for php 4.2.0 and up.随便数播种，4.2.0以后不需要了。
		$charid = strtoupper ( md5 ( uniqid ( rand (), true ) ) ); //根据当前时间（微秒计）生成唯一id.
		$hyphen = chr ( 45 ); // "-"
		$uuid = '' . //chr(123)// "{"
			substr ( $charid, 0, 8 ) . $hyphen . substr ( $charid, 8, 4 ) . $hyphen . substr ( $charid, 12, 4 ) . $hyphen . substr ( $charid, 16, 4 ) . $hyphen . substr ( $charid, 20, 12 );
		//.chr(125);// "}"
	}
	return str_replace(['{','}'],['',''],$uuid);
}

/**
 * @param $array
 * @param $field
 * @return array
 * 二维数组的某个key值作为键
 */
function array_field($array,$field){
	$return = [];
	foreach($array as $k => $v){
		$return[$v[$field]] = $v;
	}
	return $return;
}

/**
 * @param $array
 * @param $field
 * @return array
 * 二维数组的某个key值作为一个新一维数组返回
 */
function array_field_1($array,$field){
	$return = [];
	foreach($array as $k => $v){
		$return[] = $v[$field];
	}
	return $return;
}

/**
 * @param $type
 * @param $field
 * @return bool|string
 * base64 上传图片
 */
function base64_upload($type,$field){
	$base64 = request($field);
	$file_name_pre = '/storage/'.$type.'/'.date('Y-m-d').'/';
	
	\Validator::make(request()->all(),[
		'image'		=> 'bail|required',
	],[
		'image.required'	=> '未检测到图片文件',
	])->validate();
	
	if(strpos($base64 , "base64,")){
		$base64 = explode('base64,' , $base64)[1];
	}
	$base64 = base64_decode($base64);
	if(empty($base64))
		throw new \App\Exceptions\ApiException('图片解码失败，无法识别的文件');
	
	$file_name = $file_name_pre.uniqid(date('Ymd').rand('1000','9999')).'.jpg';
	$save_path = '.'.$file_name;
	if(!is_dir('.'.$file_name_pre)){
		mkdir('.'.$file_name_pre,0777,true);
	}
	$puts = file_put_contents($save_path,$base64);
	if(!$puts){
		throw new \App\Exceptions\ApiException('文件写入失败，请检查服务器权限');
	}
	$fileinfo = new finfo(FILEINFO_MIME_TYPE);
	$mime = $fileinfo->file($save_path);
	$mime_type = explode('/',$mime)[1] ?? 'png';
	$save_path_new = str_replace('.jpg','.'.$mime_type,$save_path);
	$file_name_new = str_replace('.jpg','.'.$mime_type,$file_name);
	rename($save_path,$save_path_new);
	$return = $file_name_new;
	return 'http://'.request()->server('HTTP_HOST').$return;
}

/**
 * @param $number
 * @return int
 * 未读消息总数控制在99个以内
 */
function group99($number){
	return $number <= 99 ? $number : 99;
}

/**
 * @param $data
 * @return mixed
 * 把数据库查询/自由拼接的数据统一转成数组
 */
function to_array($data){
	$return = json_decode(json_encode($data),true);
	return $return;
}


/**
 * @param $key
 * @param $callback
 * @param int $timeout
 * @return mixed
 * 利用匿名函数快速缓存
 */
function cache_callback($key,$callback,$timeout_minutes = 0){
	$value = cache($key);
	if($value){
		return $value;
	}else{
		$data = $callback();
		dump($data);
		cache([$key=>$data],$timeout_minutes);
		return $data;
	}
}